//
//  MyList.m
//  ProductDemo
//
//  Created by hoho on 14-11-4.
//  Copyright (c) 2014年 hoho. All rights reserved.
//

#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "UIView+Toast.h"
#import "UIImageView+WebCache.h"
#import "AppConstants.h"
#import "MyList.h"

@implementation MyList {
    NSInteger page;
}

#pragma mark 加载数据
- (void) loadData : (void (^)(NSArray *))success : (void (^)(NSError *))failure {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *p = [NSString stringWithFormat: @"%ld",(long)page];
    [_parameter addEntriesFromDictionary:@{@"page":p}];
    //NSLog(@"%@",_parameter);
    
    //NSDictionary *parameters = @{@"page":p,@"do":@"Product/index"};
    [manager POST:HOHOServerURL parameters:_parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSDictionary *jsonDict = (NSDictionary *) responseObject;
        NSArray *list = [jsonDict objectForKey:@"data"];
        success(list);
        [_tableV reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);
    }];
}


#pragma mark - 集成下拉刷新、上拉加载更多
- (void)setupRefresh {
    //设置下拉刷新 dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [_tableV addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    //自动刷新(一进入程序就下拉刷新)
    [_tableV headerBeginRefreshing];
    //设置上拉加载更多
    [_tableV addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 下拉刷新
- (void)headerRereshing {
    page = 1;
    [self loadData:^(NSArray *list) {//加载成功
        _data = [list copy];
        [_tableV headerEndRefreshing];//结束刷新状态
    }:^(NSError *error) {//加载失败
        [_tableV headerEndRefreshing];//结束刷新状态
        [_view makeToast:[error localizedDescription]];
    }];
}

#pragma mark 上拉加载更多
- (void)footerRereshing {
    page++;
    [self loadData:^(NSArray *list){//加载成功
        _data = [[_data arrayByAddingObjectsFromArray:list] copy];
        [_tableV footerEndRefreshing];//结束加载状态
        if(list.count == 0){
            //[_tableV removeFooter];//移除底部加载更多
            [_view makeToast:@"没有更多了"];
        }
    }:^(NSError *error){//加载失败
        [_tableV footerEndRefreshing];//结束加载状态
        [_view makeToast:[error localizedDescription]];
    }];
}

@end
